import sleep from "sleep-promise"
import Store from "electron-store"
import { changeProgress } from "../index"
import { createWindow, loadUrl } from "./browser"

export class Title{
    url: string
    win!: Electron.BrowserWindow
    page: number = 1
    link: Set<string>
    storage: Store<any>

    constructor(url: string, key: string) {
        let temp = url.split("/")
        if ( ! /p\d+?/.test(temp[temp.length - 1]) ) {
            url += url[url.length - 1] == "/" ? "p1" : "/p1"
        }

        this.url = url
        this.storage = new Store()
        let link = this.storage.get(key + "_link", [])
        console.log(link)
        this.link = new Set()
        for(var i = 0; i < link.length; i++) {
            this.link.add(link[i])
        }
    }

    async init(key:string) {
        this.win = await createWindow(this.url, key)
        await this.getPage(key)

        return this.win
    }

    async reload(key:string) {
        await loadUrl(this.win, this.url, key)
    }

    async clime(key:string):Promise<any> {
        console.log("总页数：" + this.page )
        for (let i = 1; i <= this.page; i++) {
            this.url = this.url.replace(/p\d+/, "p" + i)
            console.log("i:" + i + "\n" + this.storage.get('link'))
            await loadUrl(this.win, this.url, key)
            await this.getLink()
            changeProgress('getLinkProcess', i / this.page)
            // await sleep(Math.random() * 3000)
        }

        let res:Array<string> = []
        this.link.forEach(element => {
            res.push(element)
        });

        this.storage.set(key+"_link", res)
        console.log(this.storage.get(key+"_link"));
        return this.link
    }

    async getPage(key:string) {
        let res = await this.win.webContents.executeJavaScript("function " + this.getPageJS.toString() + ";getPageJS();")
        if (res == null) {
            await this.reload(key);
            await this.getPage(key)
        }
        this.page = res == 0 ? this.page : res;
    }

    async getLink() {
        let link = await this.win.webContents.executeJavaScript("function " + this.getLinkJS.toString() + ";getLinkJS();")
        console.log(link)
        for (let i = 0; i < link.length; i++) {
            this.link.add(link[i])
        }
    }

    public getLinkJS() {
        let res = []
        try {
            let link = document.querySelectorAll('#shop-all-list > ul > li > div.txt > div.comment > a.mean-price')
            for (let i = 0; i < link.length; i++) {
                let temp = link[i].getAttribute("href")
                if (temp != null) {
                    res.push(temp)
                }
            }
        } catch (error) {
            console.log("getLinkJS", error);
        }

        return res;
    }

    public getPageJS() {
        try {
            var page = document.querySelectorAll('a.pagelink')
            console.log("page", page);
            if (page.length == 0) return 0;
            var num = page[page.length - 1].textContent
            return num;
        } catch (error) {
            return null;
        }
    }
}